<template>
<div>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-width="formLabelWidth" class="demo-ruleForm">
    <el-form-item :label="$t('Protocol')" prop="protocol">
        <el-radio-group v-model="ruleForm.protocol">
            <el-radio label="IPV4"></el-radio>
            <!--<el-radio label="IPV6" disabled></el-radio>-->
        </el-radio-group>
    </el-form-item>
    <el-form-item :label="$t('IP address')" prop="ipaddr">
        <el-input v-model="ruleForm.ipaddr" size="small"></el-input>
    </el-form-item>
    <el-form-item :label="$t('Operate')">
        <!--<el-button type="primary" @click="addIpaddr(ruleForm.ipaddr)" size="small">{{$t('Add')}}</el-button>-->
        <el-button type="primary" @click="scan(ruleForm.ipaddr)" size="small">{{$t('Scan')}}</el-button>
    </el-form-item>
    <!--<el-form-item :label="$t('IP List')">
        <div class="ip-tag-item">
        <el-tag
            :key="tag"
            v-for="tag in ipaddrs"
            :closable="true"
            :close-transition="false"
            @close="handleCloseTag(tag)"
            class="ip-tag"
        >
        {{tag}}
        </el-tag>
        </div>
    </el-form-item>-->
    <el-form-item>
        <span class="span-title-left">VLAN</span>
        <span class="ip-span vlan-span" id="vlan">
            <li v-for="(item,index) in vlanData" :key="index">{{item}}</li>
        </span>
        <span class="span-title-mid">HUB</span>
        <span class="ip-span vlan-span" id="hub">
            <li v-for="(item,index) in hubData" :key="index">{{item}}</li>
        </span>
        <span class="span-title-right">IP</span>
        <span class="ip-span" id="ip">
            <li v-for="(item,index) in ipData" :key="index">{{item}}</li>
        </span>
    </el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
    <el-button type="success" @click="autoCreateMap">{{$t('OK')}}</el-button>
    <el-button type="danger" @click="cancelCreateMap">{{$t('Cancel')}}</el-button>
</div>
</div>
</template>

<script>
import topoApi from 'api/topo'
import {IMAGES_ID} from 'common/resTypeEnum'
// import eventHubs from 'common/eventHubs'
const ImgServer = ''
const ImgExchanger = '';
export default {
    data() {
        return {
            formLabelWidth: '70px',
            ipaddrs: [],
            ruleForm: {
                protocol: 'IPV4',
                ipaddr: ''
            },
            rules: {
                ipaddr: [
                    { required: true, message: this.$t('Please input ipaddr'), trigger: 'blur' }
                ],
                protocol: [
                    { required: true, message: this.$t('Please select'), trigger: 'change' }
                ]
            },
            allData: {},
            vlanData: [],
            hubData: [],
            ipData: [],
            curVlan: '',
            coreIpaddr: '',
            coreIpaddrSelementid: '',
            coreIpaddrName: ''
        }
    },
    mounted() {
        this.addEventListener();
    },
    props: [
        "graphView"
    ],
    methods: {
        addEventListener() {
            const self = this;
            $("#vlan").on("click", "li", function() {      
                $(this).siblings('li').removeClass('selected');
                $(this).addClass('selected');
                const vlan = $(this).text();
                self.curVlan = vlan;
                self.hubData = Object.keys(self.allData[vlan]);
            }); 

            $("#hub").on("click", "li", function() {      
                $(this).siblings('li').removeClass('selected');
                $(this).addClass('selected');
                const hub = $(this).text();
                const hubData = self.allData[self.curVlan];
                if (hubData != null && hubData != undefined) {
                    self.ipData = hubData[hub];
                }
            }); 

            // eventHubs.getEventHub().$on('topoGraphView', (topoGraphView) => { //Hub接收事件
            //     self.graphView = topoGraphView;
            //     console.log('graphView',self.graphView);
            // }); 
        },
        autoCreateMap() {
            const self = this;
            if (self.coreIpaddr == '') {
                this.$message({type:warning, message:this.$t('Please scan ipaddr first')});
                return;
            }
            let curSysmapid = this.$store.state.topo.sysmapid; // 当前拓扑图ID
            const dataModel = this.graphView.getDataModel();
            const graphDataList = dataModel.getDatas();
            const hasData = graphDataList._as.length > 0;
            if (hasData) {
                // self.$confirm('当前拓扑图有数据，确定删除重建吗?', self.$t('Prompt'), {
                //     type: 'warning'
                // }).then(() => {
                //     Ajax.syncQuery('/dirms/monitor/sysmap/delete/'+curSysmapid, {}, function(response) {
                //         self.$message({
                //             type: 'success',
                //             message: self.$t('Deleted Successfully')
                //         });

                //         const sysmapname = self.coreIpaddr;
                //         let newTmpSysmap = {};
                //         newTmpSysmap.name = sysmapname;
                //         newTmpSysmap.busType = '0';
                //         newTmpSysmap.width = '200';
                //         newTmpSysmap.height = '200';
                //         console.log('newTmpSysmap', newTmpSysmap);
                //         Ajax.syncQuery('/dirms/monitor/sysmap/create', newTmpSysmap, function(response) {
                //         // topoApi.createSysmap(newTmpSysmap).then(response => {
                //             const reslt = response;
                //             if (reslt == null || reslt == undefined || reslt == '') {
                //                 self.$message({type: 'error', message: self.$t('Failed to create') + ', ' + reslt.errorMsg});
                //                 self.$message({type: 'error', message: self.$t('already existed',{obj: sysmapname})});
                //                 return;
                //             } else {
                //                 curSysmapid = reslt.sysmapid;
                //             }
                //         });
                //     });
                // }).catch(() => {
                //     self.$message({
                //         type: 'info',
                //         message: self.$t('Cancel to delete')
                //     });
                //     return;
                // });

                self.$message({
                    type: 'warning',
                    message: '当前拓扑图有数据，请先清除！'
                });
                return;
            }

            

            // 提示
            // self.$confirm('是否确定自动创建拓扑图?', self.$t('Prompt'), {
            //     type: 'warning'
            // }).then(() => {
            //     self.$message({
            //         type: 'info',
            //         message: '已经开始创建，请稍等几分钟！'
            //     });
            // }).catch(() => {
            //     self.$message({
            //         type: 'info',
            //         message: self.$t('Cancel to create')
            //     });
            //     return;
            // });


            // 组合参数
            let paramMap = {};
            $.each(Object.values(self.allData), function() {
                for (let [key, value] of Object.entries(this)) {
                    paramMap[key] = value;    
                }
            });
            
            // console.log('curSysmapid', curSysmapid);
            // 获取所有host的编号
            topoApi.autoCreateSysmap(curSysmapid, paramMap).then(response => {
                let selements = [];
                let hubIpaddrMap = {};
                let hubIpaddrHostIdMap = {};
                if (response.status == 200) {
                    const newExchangerData = response.data;
                    for (let [hubHostid, hubMap] of Object.entries(newExchangerData)) {
                        for (let [hubIpaddr, ipaddrArr] of Object.entries(hubMap)) {
                            if (hubIpaddr == self.coreIpaddr ||  
                            (hubIpaddr.substring(0, hubIpaddr.lastIndexOf('.')) == self.coreIpaddr.substring(0, self.coreIpaddr.lastIndexOf('.')) && 
                                hubIpaddr.substring(hubIpaddr.lastIndexOf('.')+1) == '254')) {
                                // hubipaddr 为核心交换机ip
                                // 在当前拓扑图添加元素
                                let element = {};
                                element.label = hubIpaddr;
                                element.elementid = hubHostid;
                                element.sysmapid = curSysmapid;
                                element.elementtype = "0";
                                element.iconid_off = IMAGES_ID.router96;
                                selements.push(element);

                                // 添加核心交换机关联设备ip列表
                                $.each(ipaddrArr, function() {
                                    const ipaddrMap = this;
                                    let [ipTmpArr] = Object.entries(ipaddrMap);
                                    let element = {};
                                    element.label = ipTmpArr[1];
                                    element.elementid = ipTmpArr[0];
                                    element.sysmapid = curSysmapid;
                                    element.elementtype = "0";
                                    element.iconid_off = IMAGES_ID.router24;
                                    selements.push(element);
                                });
                            } else {
                                // hubIpaddr 为非核心交换机IP
                                hubIpaddrMap[hubIpaddr] = ipaddrArr;
                                hubIpaddrHostIdMap[hubIpaddr] = hubHostid;
                            }
                        }
                    }

                    // 添加hubIpaddr 到selements
                    // $.each(Object.keys(hubIpaddrMap), function() {
                        // let element = {};
                        // element.label = this;
                        // element.elementid = hubIpaddrHostIdMap[this];
                        // element.sysmapid = curSysmapid;
                        // element.elementtype = "1";
                        // element.iconid_off = "152";
                        // selements.push(element);
                    // });

                    let links = [];
                    // 创建拓扑图元素
                    topoApi.createMapElement(selements).then( response => {
                        if (response.status == 200) {
                            const elementData = response.data;
                            let iFlag = 0;
                            $.each(elementData, function() {
                                if (iFlag == 0) {
                                    self.coreIpaddrSelementid = this.selementid;
                                    iFlag = 1;
                                } else {
                                    if (self.coreIpaddrSelementid != '') {
                                        let linkData = {};
                                        linkData.sysmapid = curSysmapid;
                                        linkData.selementid1 = self.coreIpaddrSelementid;
                                        linkData.selementid2 = this.selementid;
                                        linkData.drawtype = "0";
                                        linkData.color = "00CC00";
                                        linkData.label = '';
                                        links.push(linkData);
                                    }
                                }                                

                                if (!hasData) {
                                    // 创建图形元素
                                    var newNode = new ht.Node();
                                    newNode.setId(this.selementid);
                                    newNode.setName(this.label);
                                    newNode.setToolTip(this.label);
                                    newNode.setAttr("data", this);
                                    newNode.setStyle("label.align", "left");
                                    if (!self.isObjBlank(self.sysIcons[this.iconid_off])) {
                                        const iconObj = self.sysIcons[this.iconid_off];
                                        if (!self.isObjBlank(iconObj.imageformat)) {
                                            newNode.setImage('data:'+ iconObj.imageformat+';base64,' + iconObj.image);  
                                        } else {
                                            newNode.setImage('data:image/png;base64,' + iconObj.image);
                                        }
                                    } else {
                                        newNode.setImage(ImgServer);
                                    }
                                    newNode.setPosition(100, 100);
                                    dataModel.add(newNode);
                                }
                            });
                            
                            // 建立连接
                            topoApi.addMapLinks(links).then( response => {
                                const newLinkData = response.data;

                                if (!hasData) {
                                    $.each(newLinkData, function() {
                                        var link = new ht.Edge(); //创建线,设置id
                                        link.setId(this.linkid);
                                        link.setAttr("data", this); //线的各种数据都存入线中
                                        link.setSource(dataModel.getDataById(this.selementid1));
                                        link.setTarget(dataModel.getDataById(this.selementid2));
                                        link.setStyle("edge.color", '#' + this.color);
                                        link.setName(this.label);
                                        dataModel.add(link); //添加到网元容器中
                                    });
                                    

                                    self.layout(); // 重新自动布局
                                }
                                // self.$message({type:'success', message: self.$t('Created Successfully')});
                            }).catch( err => {
                                self.$message({type:'error', message: self.$t('Failed to create')});
                            });
                        }




                        self.layout(); // 重新自动布局
                        // 建立hub拓扑图
                        let parselements = [];
                        // console.log('hubIpaddrMap', hubIpaddrMap);
                        $.each(Object.keys(hubIpaddrMap), function() {
                            let newTmpSysmap = {};
                            const hubIpaddrTmp = this; 
                            // console.log('hubIpaddrTmp', hubIpaddrTmp);
                            newTmpSysmap.name = self.coreIpaddrName+'子拓扑图('+hubIpaddrTmp+')';
                            newTmpSysmap.busType = '0';
                            newTmpSysmap.width = '200';
                            newTmpSysmap.height = '200';

                            topoApi.syncQueryMapByName({name:newTmpSysmap.name}, function(response) {
                                // console.log('findtopoName', response);
                                if (response.sysmapid != null) {
                                    topoApi.syncDeleteSysmap(response.sysmapid, function(deleteresponse) {
                                        console.log('delete topo name: ');
                                    });
                                }
                            });

                            topoApi.syncCreateSysmap(newTmpSysmap, function(response) {
                            // topoApi.createSysmap(newTmpSysmap).then(response => {
                                const reslt = response;
                                // console.log('reslt response', reslt);
                                if (reslt != null && reslt != undefined && reslt != '') {
                                    self.$message(self.$t("Created Successfully"));

                                    // 将hub添加到父拓扑
                                    let parelement = {};
                                    parelement.label = self.coreIpaddrName+'子拓扑图('+hubIpaddrTmp+')';
                                    parelement.elementid = reslt.sysmapid;
                                    parelement.sysmapid = curSysmapid;
                                    parelement.elementtype = "1";
                                    parelement.iconid_off = IMAGES_ID.hub64;
                                    parselements.push(parelement);

                                    // console.log('parselements', parselements);


                                    // 添加子拓扑图元素
                                    const ipaddrArr = hubIpaddrMap[hubIpaddrTmp];
                                    const hubHostid = hubIpaddrHostIdMap[hubIpaddrTmp]

                                    let childSelements = [], childLinks = [];
                                    let element = {};
                                    element.label = hubIpaddrTmp;
                                    element.elementid = hubHostid;
                                    element.sysmapid = reslt.sysmapid;
                                    element.elementtype = "0";
                                    element.iconid_off = IMAGES_ID.router96;
                                    childSelements.push(element);

                                    // 添加hub关联设备ip列表
                                    $.each(ipaddrArr, function() {
                                        const ipaddrMap = this;
                                        let [ipTmpArr] = Object.entries(ipaddrMap);
                                        let element = {};
                                        element.label = ipTmpArr[1];
                                        element.elementid = ipTmpArr[0];
                                        element.sysmapid = reslt.sysmapid;
                                        element.elementtype = "0";
                                        element.iconid_off = IMAGES_ID.router24;
                                        childSelements.push(element);
                                    });

                                    // console.log('childSelements', childSelements);

                                    topoApi.createMapElement(childSelements).then( response => {
                                        // console.log('chiled elemen response', response);
                                        if (response.status == 200) {
                                            const elementData = response.data;
                                            let iFlag = 0;
                                            let hubIpaddrSelementid = '';
                                            $.each(elementData, function() {
                                                if (iFlag == 0) {
                                                    hubIpaddrSelementid = this.selementid;
                                                    iFlag = 1;
                                                } else {
                                                    if (hubIpaddrSelementid != '') {
                                                        let linkData = {};
                                                        linkData.sysmapid = reslt.sysmapid;
                                                        linkData.selementid1 = hubIpaddrSelementid;
                                                        linkData.selementid2 = this.selementid;
                                                        linkData.drawtype = "0";
                                                        linkData.color = "00CC00";
                                                        linkData.label = '';
                                                        childLinks.push(linkData);
                                                    }
                                                }                                

                                                // 创建图形元素
                                                // var newNode = new ht.Node();
                                                // newNode.setName(this.label);
                                                // if (!self.isObjBlank(self.sysIcons[this.iconid_off])) {
                                                //     const iconObj = self.sysIcons[this.iconid_off];
                                                //     if (!self.isObjBlank(iconObj.imageformat)) {
                                                //         newNode.setImage('data:'+ iconObj.imageformat+';base64,' + iconObj.image);  
                                                //     } else {
                                                //         newNode.setImage('data:image/png;base64,' + iconObj.image);
                                                //     }
                                                // } else {
                                                //     newNode.setImage(ImgServer);
                                                // }
                                                // newNode.setPosition(100, 100);
                                                // dataModel.add(newNode);
                                            });
                                            
                                            // 建立连接
                                            // console.log('cchildLinkse', childLinks);
                                            topoApi.addMapLinks(childLinks).then( response => {
                                                // console.log('childLinks response', response);
                                                // console.log('linksresponse', response);
                                                // const newLinkData = response.data;

                                                // $.each(newLinkData, function() {
                                                //     var link = new ht.Edge(); //创建线,设置id
                                                //     link.setId(this.linkid);
                                                //     link.setAttr("data", this); //线的各种数据都存入线中
                                                //     link.setSource(dataModel.getDataById(this.selementid1));
                                                //     link.setTarget(dataModel.getDataById(this.selementid2));
                                                //     link.setStyle("edge.color", '#' + this.color);
                                                //     link.setName(this.label);
                                                //     dataModel.add(link); //添加到网元容器中
                                                // });

                                                // self.layout(); // 重新自动布局
                                                // self.$message({type:'success', message: self.$t('Created Successfully')});
                                            }).catch( err => {
                                                console.log('addmaplink err', err);
                                                self.$message({type:'error', message: self.$t('Failed to create')});
                                            });
                                        }
                                    }).catch(err => {
                                        console.log('createmapelemnet err', err);
                                        self.$message.error(self.$t('Failed to create'));
                                    });
                                }
                            });
                        });



                        // 创建父拓扑图元素（hub节点）
                        topoApi.createMapElement(parselements).then( response => {
                            if (response.status == 200) {
                                let parchildLinks = [];
                                const elementData = response.data;
                                $.each(elementData, function() {
                                    
                                    if (self.coreIpaddrSelementid != '') {
                                        let linkData = {};
                                        linkData.sysmapid = curSysmapid;
                                        linkData.selementid1 = self.coreIpaddrSelementid;
                                        linkData.selementid2 = this.selementid;
                                        linkData.drawtype = "0";
                                        linkData.color = "00CC00";
                                        linkData.label = '';
                                        parchildLinks.push(linkData);
                                    }

                                    if (!hasData) {
                                        // 创建图形元素
                                        var newNode = new ht.Node();
                                        newNode.setId(this.selementid);
                                        newNode.setName(this.label);
                                        newNode.setToolTip(this.label);
                                        newNode.setAttr("data", this);
                                        newNode.setStyle("label.align", "left");
                                        if (!self.isObjBlank(self.sysIcons[this.iconid_off])) {
                                            const iconObj = self.sysIcons[this.iconid_off];
                                            if (!self.isObjBlank(iconObj.imageformat)) {
                                                newNode.setImage('data:'+ iconObj.imageformat+';base64,' + iconObj.image);  
                                            } else {
                                                newNode.setImage('data:image/png;base64,' + iconObj.image);
                                            }
                                        } else {
                                            newNode.setImage(ImgServer);
                                        }
                                        newNode.setPosition(100, 100);
                                        dataModel.add(newNode);
                                    }
                                });
                                
                                // 建立连接
                                topoApi.addMapLinks(parchildLinks).then( response => {
                                    const newLinkData = response.data;

                                    if (!hasData) {
                                        $.each(newLinkData, function() {
                                            var link = new ht.Edge(); //创建线,设置id
                                            link.setId(this.linkid);
                                            link.setAttr("data", this); //线的各种数据都存入线中
                                            link.setSource(dataModel.getDataById(this.selementid1));
                                            link.setTarget(dataModel.getDataById(this.selementid2));
                                            link.setStyle("edge.color", '#' + this.color);
                                            link.setName(this.label);
                                            dataModel.add(link); //添加到网元容器中
                                        });

                                        self.layout(); // 重新自动布局
                                    }
                                    self.$message({type:'success', message: self.$t('Created Successfully')});
                                }).catch( err => {
                                    console.log('par addmaplinks err', err);
                                    self.$message({type:'error', message: self.$t('Failed to create')});
                                });
                            }
                        }).catch(err => {
                            console.log('par createMapElement err', err);
                            self.$message.error(self.$t('Failed to create'));
                        });

                    }).catch(err => {
                        console.log('root createMapElement err', err);
                        self.$message.error(self.$t('Failed to create'));
                    });
                }
            }).catch(err =>{
                console.log('auto createmap err', err);
            });
            
            this.$emit('transferCloseDialog', this.$t('Created Successfully'));
        },
        cancelCreateMap() {
            this.$emit('transferCloseDialog', this.$t('Cancel to create'));
        },
        // addIpaddr(ipaddr) {
        //     if (ipaddr == '') {
        //         this.$message({type:'warning',message: this.$t('Please input ipaddr')});
        //         return;
        //     }
        //     if ($.inArray(ipaddr, this.ipaddrs) != -1) {
        //         this.$message({type:'warning',message: this.$t('already existed',{obj: ipaddr})});
        //         return;
        //     }
        //     this.ipaddrs.push(ipaddr);
        // },
        handleCloseTag(tag) {
            this.ipaddrs.splice(this.ipaddrs.indexOf(tag), 1);
        },
        scan(ipaddr) {
            const self = this;
            if (ipaddr == '') {
                this.$message({type:'warning',message: this.$t('Please input ipaddr')});
                return;
            }
            this.coreIpaddr = ipaddr;
            // todo list 查找ipaddr的hostid

            topoApi.queryHostByName(ipaddr).then(response => {
                console.log('ipaddr', response);
                if (response.data == null || response.status != 200) {
                    self.$message({type:'warning',message: self.$t('scan failed')});
                    return;  
                }

                self.coreIpaddrName = response.data.name;
                topoApi.queryVlanAndIp(response.data.hostid).then(response => {
                    self.allData = response.data;
                    self.vlanData = Object.keys(response.data);
                }).catch(err => {
                    self.$message({type:'warning',message: self.$t('get vlan data failed')});
                });
            }).catch(err => {
                self.$message({type:'warning',message: self.$t('scan failed')});
            });
        },
        layout() {
            const self = this;
            // 布局设置
            const autoLayout = new ht.layout.AutoLayout(this.graphView);
            // this.autoLayout.setAnimate(animate);
            autoLayout.layout('symmetric', function() {
                self.graphView.fitContent(true);
            });
        },
        isObjBlank(obj) {
            return (obj === null) || (obj === undefined) || (obj === '');
        }
    },
    computed: {
        sysIcons() {
            return this.$store.state.topo.sysIcons;
        }
    },
}
</script>

<style>
    .ip-tag-item {
        border: 1px solid #99A9BF; 
        height:40px;
    }
    .vlan-span > li:hover {
        background-color: #dff0d8;
        color: #3c763d;
    }

    span > li {
        line-height: 16px;
    }

    .ip-tag {
        margin:2px 5px;
    }

    .selected {
        background-color: #dff0d8;
        color: #3c763d;
    }

    .ip-span {
        float: left;
        width: 30%;
        height: 200px;
        border: 1px solid #99A9BF;
        padding-left: 10px;
        overflow: auto;
        margin-top: 20px;
    }

    .vlan-span {
        margin-right: 5px;
    }

    .span-title-left {
        position: absolute;
        top: -18px;
        left: 2%
    }

    .span-title-mid {
        position: absolute;
        top: -18px;
        right: 58%
    }

    .span-title-right {
        position: absolute;
        top: -18px;
        right: 28%
    }
</style>
